#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
主窗口界面模块
支持提供商-模型层级选择的配置界面
"""

import os
from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                             QPushButton, QLabel, QFileDialog, QMessageBox, 
                             QLineEdit, QComboBox, QTextEdit)
from PySide6.QtCore import Qt, QSettings
from PySide6.QtGui import QPixmap
from core.image_processor import ImageProcessor
from core.cad_exporter import CADExporter
from config import get_available_providers, get_provider_models, get_model_info, update_user_config, get_current_config, get_export_formats, update_export_formats


class MainWindow(QMainWindow):
    """
    主窗口类，提供图形用户界面
    """
    def __init__(self):
        """
        初始化主窗口
        """
        super().__init__()
        self.setWindowTitle("Picture to CAD")
        self.setGeometry(100, 100, 800, 600)
        
        # 创建中央部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        
        # 创建配置区域
        config_group = QVBoxLayout()
        
        # 地区、提供商和模型选择（同一行）
        region_provider_layout = QHBoxLayout()
        
        # 地区选择
        self.region_label = QLabel("地区:")
        self.region_combo = QComboBox()
        
        # 从配置加载地区选项
        from config import get_config_manager
        manager = get_config_manager()
        regions = manager.get_available_regions()
        for region_code in regions:
            display_name = manager.get_region_display_name(region_code)
            self.region_combo.addItem(display_name, region_code)
            
        self.region_combo.currentTextChanged.connect(self.on_region_changed)
        self.region_combo.setFixedWidth(100)  # 设置固定宽度
        
        # 提供商选择
        self.provider_label = QLabel("提供商:")
        self.provider_combo = QComboBox()
        self.provider_combo.currentTextChanged.connect(self.on_provider_changed)
        self.provider_combo.setFixedWidth(150)  # 设置固定宽度
        
        # 模型选择
        self.model_label = QLabel("模型:")
        self.model_combo = QComboBox()
        self.model_combo.currentTextChanged.connect(self.on_model_changed)
        self.model_combo.setFixedWidth(150)  # 设置固定宽度
        
        # 添加到同一行布局
        region_provider_layout.addWidget(self.region_label)
        region_provider_layout.addWidget(self.region_combo)
        region_provider_layout.addStretch()  # 添加间距
        region_provider_layout.addWidget(self.provider_label)
        region_provider_layout.addWidget(self.provider_combo)
        region_provider_layout.addStretch()  # 添加间距
        region_provider_layout.addWidget(self.model_label)
        region_provider_layout.addWidget(self.model_combo)
        
        # API密钥输入
        api_layout = QHBoxLayout()
        self.api_key_label = QLabel("API密钥:")
        self.api_key_input = QLineEdit()
        self.api_key_input.setPlaceholderText("输入您的API密钥")
        self.api_key_input.setEchoMode(QLineEdit.Password)
        api_layout.addWidget(self.api_key_label)
        api_layout.addWidget(self.api_key_input)
        
        # 模型描述
        self.model_desc = QTextEdit()
        self.model_desc.setMaximumHeight(60)
        self.model_desc.setReadOnly(True)
        self.model_desc.setStyleSheet("background-color: #f0f0f0; border: 1px solid #ccc;")
        
        # 保存按钮
        self.save_config_button = QPushButton("保存配置")
        self.save_config_button.clicked.connect(self.save_api_key)
        
        config_group.addLayout(region_provider_layout)
        config_group.addLayout(api_layout)
        config_group.addWidget(self.model_desc)
        config_group.addWidget(self.save_config_button)
        
        layout.addLayout(config_group)
        
        # 创建导出格式组
        from PySide6.QtWidgets import QGroupBox, QCheckBox
        export_group = QGroupBox("CAD导出格式")
        export_layout = QVBoxLayout()
        
        # 2D格式
        self.dxf_check = QCheckBox("DXF (AutoCAD)")
        self.svg_check = QCheckBox("SVG (矢量图)")
        self.pdf_check = QCheckBox("PDF (文档)")
        
        # 3D格式
        self.stl_check = QCheckBox("STL (3D打印)")
        self.obj_check = QCheckBox("OBJ (3D模型)")
        self.step_check = QCheckBox("STEP (工业标准)")
        self.iges_check = QCheckBox("IGES (交换格式)")
        
        # 参数化格式
        self.scad_check = QCheckBox("OpenSCAD脚本")
        
        # 添加到布局
        export_layout.addWidget(QLabel("2D格式:"))
        export_layout.addWidget(self.dxf_check)
        export_layout.addWidget(self.svg_check)
        export_layout.addWidget(self.pdf_check)
        
        export_layout.addWidget(QLabel("3D格式:"))
        export_layout.addWidget(self.stl_check)
        export_layout.addWidget(self.obj_check)
        export_layout.addWidget(self.step_check)
        export_layout.addWidget(self.iges_check)
        
        export_layout.addWidget(QLabel("参数化格式:"))
        export_layout.addWidget(self.scad_check)
        
        # 保存导出格式按钮
        self.save_export_button = QPushButton("保存导出格式")
        self.save_export_button.clicked.connect(self.save_export_formats)
        export_layout.addWidget(self.save_export_button)
        
        export_group.setLayout(export_layout)
        layout.addWidget(export_group)
        
        # 状态标签
        self.status_label = QLabel("状态: 准备就绪")
        self.status_label.setStyleSheet("color: blue; font-weight: bold;")
        layout.addWidget(self.status_label)
        
        # 创建上传按钮
        self.upload_button = QPushButton("上传图片")
        self.upload_button.clicked.connect(self.upload_image)
        layout.addWidget(self.upload_button)
        
        # 创建预览标签
        self.preview_label = QLabel("预览区域")
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setMinimumSize(400, 300)
        self.preview_label.setStyleSheet("border: 1px solid black;")
        layout.addWidget(self.preview_label)
        
        # 创建下载按钮
        self.download_button = QPushButton("下载CAD文件")
        self.download_button.clicked.connect(self.download_cad)
        layout.addWidget(self.download_button)
        
        # 初始化文件路径和核心模块
        self.image_path = None
        self.processor = ImageProcessor()
        self.exporter = CADExporter()
        
        # 加载保存的配置
        self.load_saved_config()
        
        # 更新状态显示
        self.update_status_display()
        
        # 初始化提供商和模型
        self.init_provider_models()
        
        # 初始化导出格式配置
        self.init_export_formats()
    
    def load_saved_config(self):
        """加载保存的配置"""
        from config import get_config_manager
        manager = get_config_manager()
        provider, model = manager.get_current_provider_model()
        api_key = manager.get_api_key(provider)
        
        # 根据提供商设置地区
        if provider:
            provider_config = manager.get_provider_config(provider)
            region_code = provider_config.get('region', 'US')
            
            # 查找对应的显示名称索引
            for i in range(self.region_combo.count()):
                if self.region_combo.itemData(i) == region_code:
                    self.region_combo.setCurrentIndex(i)
                    break
            
            # 触发地区改变事件以更新提供商列表
            self.on_region_changed(self.region_combo.currentText())
            self.provider_combo.setCurrentText(provider)
        if model:
            self.model_combo.setCurrentText(model)
        if api_key:
            self.api_key_input.setText(api_key)
    
    def save_api_key(self):
        """保存API密钥到配置文件"""
        provider = self.provider_combo.currentText()
        model = self.model_combo.currentText()
        api_key = self.api_key_input.text().strip()
        
        if not api_key:
            QMessageBox.warning(self, "警告", "请输入有效的API密钥")
            return
        
        try:
            # 保存到配置文件
            from config import get_config_manager
            manager = get_config_manager()
            manager.set_current_provider_model(provider, model)
            manager.update_api_key(provider, api_key)
            
            # 重新初始化处理器
            self.processor = ImageProcessor()
            
            QMessageBox.information(self, "成功", "API密钥已保存并生效")
            self.update_status_display()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}")
    
    def on_region_changed(self, display_name):
        """地区改变时更新提供商列表"""
        from config import get_config_manager
        manager = get_config_manager()
        
        # 从显示名称获取地区代码
        region_code = None
        for i in range(self.region_combo.count()):
            if self.region_combo.itemText(i) == display_name:
                region_code = self.region_combo.itemData(i)
                break
        
        if region_code:
            self.provider_combo.clear()
            providers = manager.get_providers_by_region(region_code)
            self.provider_combo.addItems(providers)
            if providers:
                self.provider_combo.setCurrentIndex(0)
    
    def on_provider_changed(self, provider):
        """提供商改变时更新模型列表"""
        self.model_combo.clear()
        try:
            models = get_provider_models(provider)
            self.model_combo.addItems(models)
            if models:
                self.model_combo.setCurrentIndex(0)
        except Exception as e:
            QMessageBox.warning(self, "警告", f"获取模型列表失败: {str(e)}")
    
    def on_model_changed(self, model):
        """模型改变时更新描述"""
        if not model:
            return
            
        try:
            from config import get_config_manager
            manager = get_config_manager()
            provider = self.provider_combo.currentText()
            
            if provider and model:
                model_info = manager.get_model_info(provider, model)
                desc = model_info.get('description', '无描述')
                self.model_desc.setText(desc)
        except Exception:
            self.model_desc.setText("无描述")
    
    def init_provider_models(self):
        """初始化提供商和模型"""
        try:
            from config import get_config_manager
            manager = get_config_manager()
            provider, model = manager.get_current_provider_model()
            
            # 初始化地区选择
            self.on_region_changed(self.region_combo.currentText())
            
            if provider:
                # 根据提供商设置地区
                provider_config = manager.get_provider_config(provider)
                region_code = provider_config.get('region', 'US')
                
                # 查找对应的显示名称索引
                for i in range(self.region_combo.count()):
                    if self.region_combo.itemData(i) == region_code:
                        self.region_combo.setCurrentIndex(i)
                        break
                
                # 更新提供商列表并选择
                self.on_region_changed(self.region_combo.currentText())
                self.provider_combo.setCurrentText(provider)
                self.on_provider_changed(provider)
                if model:
                    self.model_combo.setCurrentText(model)
                    self.on_model_changed(model)
        except Exception:
            pass

    def init_export_formats(self):
        """初始化导出格式"""
        try:
            from config import get_export_formats
            formats = get_export_formats()
            
            self.dxf_check.setChecked(formats.get('dxf', True))
            self.svg_check.setChecked(formats.get('svg', True))
            self.pdf_check.setChecked(formats.get('pdf', False))
            self.stl_check.setChecked(formats.get('stl', True))
            self.obj_check.setChecked(formats.get('obj', True))
            self.step_check.setChecked(formats.get('step', True))
            self.iges_check.setChecked(formats.get('iges', True))
            self.scad_check.setChecked(formats.get('scad', False))
            
        except Exception as e:
            print(f"初始化导出格式失败: {e}")
            # 设置默认值
            self.dxf_check.setChecked(True)
            self.svg_check.setChecked(True)
            self.pdf_check.setChecked(False)
            self.stl_check.setChecked(True)
            self.obj_check.setChecked(True)
            self.step_check.setChecked(True)
            self.iges_check.setChecked(True)
            self.scad_check.setChecked(False)
    
    def update_status_display(self):
        """更新状态显示"""
        if self.processor.configured:
            from config import get_config_manager
            manager = get_config_manager()
            provider, model = manager.get_current_provider_model()
            self.status_label.setText(f"状态: {provider} - {model} 已配置")
            self.status_label.setStyleSheet("color: green; font-weight: bold;")
        else:
            self.status_label.setText("状态: 使用示例数据，请配置API密钥")
            self.status_label.setStyleSheet("color: orange; font-weight: bold;")
    
    def upload_image(self):
        """
        上传图片并显示预览
        """
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择图片", "", "Image Files (*.png *.jpg *.jpeg)"
        )
        if file_path:
            self.image_path = file_path
            # 显示图片预览
            pixmap = QPixmap(file_path)
            # 缩放图片以适应预览区域
            scaled_pixmap = pixmap.scaled(
                self.preview_label.size(), 
                Qt.KeepAspectRatio, 
                Qt.SmoothTransformation
            )
            self.preview_label.setPixmap(scaled_pixmap)
    
    def save_export_formats(self):
        """保存导出格式设置"""
        try:
            from config import update_export_formats
            
            formats = {
                'dxf': self.dxf_check.isChecked(),
                'svg': self.svg_check.isChecked(),
                'pdf': self.pdf_check.isChecked(),
                'stl': self.stl_check.isChecked(),
                'obj': self.obj_check.isChecked(),
                'step': self.step_check.isChecked(),
                'iges': self.iges_check.isChecked(),
                'scad': self.scad_check.isChecked()
            }
            
            update_export_formats(formats)
            QMessageBox.information(self, "成功", "导出格式设置已保存")
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"保存导出格式失败: {str(e)}")

    def download_cad(self):
        """
        处理图片并下载CAD文件
        """
        if not self.image_path:
            self.preview_label.setText("请先上传图片")
            return
        
        # 调用核心模块进行图像处理和CAD转换
        elements = self.processor.process_image(self.image_path)
        
        # 生成输出文件路径
        base_name = os.path.splitext(self.image_path)[0]
        output_path = f"{base_name}.dxf"
        
        # 导出为DXF文件
        self.exporter.export_to_dxf(elements, output_path)
        
        # 提示用户文件已生成
        QMessageBox.information(self, "成功", f"CAD文件已生成: {output_path}")
        self.preview_label.setText(f"CAD文件已生成: {output_path}")